<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>学生信息管理页面</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">

    <style>
        body {
            background-color: #f8f9fa;
        }
        .header {
            background-color: #343a40;
            color: white;
        }
        .footer {
            background-color: #6c757d;
            color: white;
        }
        .search-box {
            max-width: 400px;
            margin: 20px auto;
        }
    </style>
</head>
<body>
<!-- Header -->
<header class="header text-center py-3">
    <h1>学生信息管理系统</h1>
</header>

<!-- 搜索框 -->
<div class="search-box text-center">
    <input type="text" id="searchInput" class="form-control" placeholder="搜索学生信息...">
</div>

<!-- 新增按钮 -->
<div class="text-center my-3">
    <button class="btn btn-success" data-toggle="modal" data-target="#studentModal" onclick="clearForm()">新增学生信息</button>
</div>

<!-- 学生信息展示 -->
<div class="container mt-3">
    <div class="row">
        <div class="col-md-12">
            <div id="studentInfo" class="table-responsive">
                <!-- 学生信息表格将插入到这里 -->
            </div>
            <!-- 分页导航条 -->
            <nav>
                <ul class="pagination justify-content-center" id="pagination">
                    <!-- 分页按钮将插入到这里 -->
                </ul>
            </nav>
        </div>
    </div>
</div>

<!-- 新增和修改学生的模态框 -->
<div class="modal fade" id="studentModal" tabindex="-1" aria-labelledby="studentModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="studentModalLabel">新增/修改学生信息</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="studentForm">
                    <input type="hidden" id="studentId">
                    <div class="form-group">
                        <label for="name">姓名</label>
                        <input type="text" class="form-control" id="name" required>
                    </div>
                    <div class="form-group">
                        <label for="age">年龄</label>
                        <input type="number" class="form-control" id="age" required>
                    </div>
                    <div class="form-group">
                        <label for="gender">性别</label>
                        <select class="form-control" id="gender" required>
                            <option value="Male">男</option>
                            <option value="Female">女</option>
                            <option value="Other">其他</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="contactNumber">联系方式</label>
                        <input type="text" class="form-control" id="contactNumber" required>
                    </div>
                    <div class="form-group">
                        <label for="avatarUrl">头像 URL</label>
                        <input type="text" class="form-control" id="avatarUrl" required>
                    </div>
                    <button type="submit" class="btn btn-primary">保存</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Footer -->
<footer class="footer text-center py-3 mt-5">
    <p>&copy; 2024 学生信息管理系统. 保留所有权利.</p>
</footer>

<!-- 引入 Bootstrap 4 和 jQuery -->
<!-- 使用 BootCDN 提供的 jQuery 和 Bootstrap 4 JS CDN -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/popper.js/2.9.3/umd/popper.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.2/js/bootstrap.min.js"></script>
<!-- Ajax 脚本 -->
<script>
    $(document).ready(function() {
        fetchStudents(1);

        $('#searchInput').on('input', function() {
            const query = $(this).val();
            fetchStudents(1, query);
        });

        $('#studentForm').on('submit', function(e) {
            e.preventDefault();
            const studentId = $('#studentId').val();
            if (studentId) {
                updateStudent(studentId);
            } else {
                addStudent();
            }
        });
    });

    function fetchStudents(page, query = '') {
        $.ajax({
            url: 'student',
            method: 'GET',
            data: {
                operation: query ? 'searchStudentsByName' : 'getStudentsByPage',
                page: page,
                pageSize: 3, // 可以根据需要调整每页显示的学生数量
                name: query
            },
            success: function(apiResult) {
                console.log('Received data:', apiResult);
                if (apiResult.code === 200) {
                    let responseData = apiResult.data; // 获取整个响应数据
                    let students = responseData.students; // 从响应数据中取出学生数据
                    let tableHtml = '<table class="table table-striped">';
                    tableHtml += '<thead class="thead-dark"><tr><th>ID</th><th>姓名</th><th>年龄</th><th>性别</th><th>联系方式</th><th>头像</th><th>操作</th></tr></thead><tbody>';
                    students.forEach(student => {
                        tableHtml += '<tr>';
                        tableHtml += '<td>' + student.studentId + '</td>';
                        tableHtml += '<td>' + student.name + '</td>';
                        tableHtml += '<td>' + student.age + '</td>';
                        tableHtml += '<td>' + student.gender + '</td>';
                        tableHtml += '<td>' + student.contactNumber + '</td>';
                        tableHtml += '<td><img src="' + student.avatarUrl + '" alt="Avatar" width="50" height="50"></td>';
                        tableHtml += '<td>';
                        tableHtml += '<button class="btn btn-primary btn-sm" onclick="editStudent(' + student.studentId + ')">修改</button> ';
                        tableHtml += '<button class="btn btn-danger btn-sm" onclick="deleteStudent(' + student.studentId + ')">删除</button>';
                        tableHtml += '</td>';
                        tableHtml += '</tr>';
                    });
                    tableHtml += '</tbody></table>';
                    $('#studentInfo').html(tableHtml);

                    // 生成分页按钮
                    generatePagination(responseData.totalPages, page);
                } else {
                    console.error('Error:', apiResult.msg);
                }
            },
            error: function(err) {
                console.error('Error fetching students:', err);
            }
        });
    }


    function generatePagination(totalPages, currentPage) {
        let paginationHtml = '';
        if (totalPages > 0) {
            paginationHtml += '<li class="page-item ' + (currentPage === 1 ? 'disabled' : '') + '">';
            paginationHtml += '<a class="page-link" href="#" onclick="fetchStudents(' + (currentPage - 1) + ')">&laquo;</a>';
            paginationHtml += '</li>';
            for (let i = 1; i <= totalPages; i++) {
                paginationHtml += `<li class="page-item ${i === currentPage ? 'active' : ''}">
                                <a class="page-link" href="#" onclick="fetchStudents(${i})">${i}</a>
                               </li>`;
            }
            paginationHtml += '<li class="page-item ' + (currentPage === totalPages ? 'disabled' : '') + '">';
            paginationHtml += '<a class="page-link" href="#" onclick="fetchStudents(' + (currentPage + 1) + ')">&raquo;</a>';
            paginationHtml += '</li>';
        }
        $('#pagination').html(paginationHtml);
    }



    function addStudent() {
        const student = {
            name: $('#name').val(),
            age: $('#age').val(),
            gender: $('#gender').val(),
            contactNumber: $('#contactNumber').val(),
            avatarUrl: $('#avatarUrl').val()
        };

        $.ajax({
            url: 'student?operation=addStudent',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(student),
            success: function(apiResult) {
                if (apiResult.code === 200) {
                    $('#studentModal').modal('hide');
                    fetchStudents(1);
                } else {
                    console.error('Error:', apiResult.msg);
                }
            },
            error: function(err) {
                console.error('Error adding student:', err);
            }
        });
    }

    function editStudent(studentId) {
        $.ajax({
            url: 'student',
            method: 'GET',
            data: {
                operation: 'getStudentById',
                studentId: studentId
            },
            success: function(apiResult) {
                if (apiResult.code === 200) {
                    const student = apiResult.data;
                    $('#studentId').val(student.studentId);
                    $('#name').val(student.name);
                    $('#age').val(student.age);
                    $('#gender').val(student.gender);
                    $('#contactNumber').val(student.contactNumber);
                    $('#avatarUrl').val(student.avatarUrl);
                    $('#studentModal').modal('show');
                } else {
                    console.error('Error:', apiResult.msg);
                }
            },
            error: function(err) {
                console.error('Error fetching student:', err);
            }
        });
    }

    function updateStudent(studentId) {
        const student = {
            studentId: studentId,
            name: $('#name').val(),
            age: $('#age').val(),
            gender: $('#gender').val(),
            contactNumber: $('#contactNumber').val(),
            avatarUrl: $('#avatarUrl').val()
        };

        $.ajax({
            url: 'student?operation=updateStudent',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(student),
            success: function(apiResult) {
                if (apiResult.code === 200) {
                    $('#studentModal').modal('hide');
                    fetchStudents(1);
                } else {
                    console.error('Error:', apiResult.msg);
                }
            },
            error: function(err) {
                console.error('Error updating student:', err);
            }
        });
    }

    function deleteStudent(studentId) {
        if (confirm('确定要删除这个学生吗？')) {
            $.ajax({
                url: 'student',
                method: 'POST',
                data: {
                    operation: 'deleteStudent',
                    studentId: studentId
                },
                success: function(apiResult) {
                    if (apiResult.code === 200) {
                        fetchStudents(1);
                    } else {
                        console.error('Error:', apiResult.msg);
                    }
                },
                error: function(err) {
                    console.error('Error deleting student:', err);
                }
            });
        }
    }

    function clearForm() {
        $('#studentId').val('');
        $('#name').val('');
        $('#age').val('');
        $('#gender').val('');
        $('#contactNumber').val('');
        $('#avatarUrl').val('');
        $('#studentModalLabel').text('新增学生信息');
    }
</script>
</body>
</html>
